<script setup lang="ts">
import YkPagination from '@yk/components/pagination/YkPagination.vue'
import { Pages } from '@typings/pages'
import YkTableColumn from '@yk/components/table-column/YkTableColumn.vue'
import { ObjectUtil } from '@utils/object-util'
import { ElForm, ElTable } from 'element-plus'
import { TableUtil } from '@utils/table-util'
import { MountedCheck } from '@/utils'
import { getSimCardListByPageAPI, simCardAlarmSettingsAPI } from '@/api/sim-card'
import { cIdStatusMap } from '@/dataset'
import { CardDTO } from '@/api/entity/sim-card'
import { InfoFilled } from '@element-plus/icons-vue'

const router = useRouter()
defineOptions({ name: 'SimManage' })

const mc = new MountedCheck()
onMounted(() => {
  searchHandle()
  mc.end()
})

onActivated(() => {
  if (mc.isMounted()) return
  getTableData()
})

// region TODO 查询
const searchParams = reactive({
  // SIM卡号
  cardno: ''
})
function searchHandle () {
  pages.pageNum = 1
  exportParams.value = ObjectUtil.copy(searchParams)
  getTableData()
}
// endregion

// region TODO 表格数据
const pages = reactive(new Pages())
const tableData = shallowRef<CardDTO[]>([])
const tableDataRef = ref<InstanceType<typeof ElTable>>()
function getTableData () {
  const loading = ElLoading.service()
  getSimCardListByPageAPI({
    ...pages.getParams(),
    param: searchParams
  }).then((res) => {
    res.result().then((rdata) => {
      tableData.value = rdata.records
      pages.total = rdata.total
    })
  })
  loading.close()
}
function delTableItem (id: string) {
  ElMessageBox.confirm('删除当前设备？', '删除提醒').then(() => {
    // delDeviceAPI({ id }).then((res) => {
    //   res.result().then(() => {
    //     getTableData()
    //   })
    // })
  })
}
// endregion

// region TODO 报警配置
const alarmNumber = ref(10)
function alarmConfig () {
  const rows = tableDataRef.value.getSelectionRows()
  if (!rows.length) {
    ElMessage.info('请勾选需要配置的物联卡')
    return
  }
  showAlarmConfigDialog()
}
function alarmConfigHandle () {
  if (ObjectUtil.isEmpty(alarmNumber.value)) {
    ElMessage.warning('阈值不可以为空')
    return
  }
  simCardAlarmSettingsAPI({
    ids: tableDataRef.value.getSelectionRows().map(item => item.id),
    alarm: alarmNumber.value
  }).then((res) => {
    res.result().then(() => {
      ElMessage.success('设置成功')
      closeAlarmConfigDialog()
      getTableData()
    })
  })
}
// 对话框
const alarmConfigDialogModel = ref(false)
function showAlarmConfigDialog () {
  alarmConfigDialogModel.value = true
}
function closeAlarmConfigDialog () {
  alarmConfigDialogModel.value = false
}
// endregion

// region TODO 导出
const exportParams = shallowRef<typeof searchParams>()
// endregion

</script>

<template>
  <div class="layout_view d-flex" style="min-height: 100%">
    <div class="c_card-page w-100 flex-1">
      <div class="c_card_header c_card-title bor-divider-b">物联卡管理</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search mt-3" @submit.prevent="searchHandle">
        <el-form-item label="条件：">
          <el-input v-model="searchParams.cardno" placeholder="请输入SIM卡号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
        <el-form-item class="float-right mr-0">
          <el-button type="primary" plain @click="alarmConfig">报警配置</el-button>
        </el-form-item>
      </el-form>
      <!--表格-->
      <el-table ref="tableDataRef" class="c_table-page w-100" stripe :data="tableData">
        <el-table-column type="selection" />
        <el-table-column label="#" type="index" :index="TableUtil.indexMethod.bind(this, pages)" />
        <yk-table-column label="卡号" prop="cardno" />
        <el-table-column label="状态" prop="">
          <template #default="scope">
            <el-tag
              :type="{ '00': 'success', '08': 'danger', '02': 'danger' }[scope.row.state || '0'] || 'info'"
              effect="dark" size="small"
            >
              {{ cIdStatusMap.get(scope.row.state || '0') }}
            </el-tag>
          </template>
        </el-table-column>
        <yk-table-column label="剩余流量（KB）" prop="surplus" />
        <el-table-column label="关联网关" prop="gateWayName">
          <template #header>
            <div class="d-flex-align-center">
              <div>关联网关</div>
              <el-popover placement="top-start" width="200px">
                <div>
                  如果显示多个网关，可能是卡号重复填写，请检查物联卡绑定是否正确
                </div>
                <template #reference>
                  <el-icon size="16" class="color-info ml-1"><InfoFilled /></el-icon>
                </template>
              </el-popover>
            </div>
          </template>
          <template #default="scope">
            <div class="overflow-ellipsis" :title="scope.row.gateWayName">{{ scope.row.gateWayName || '/' }}</div>
          </template>
        </el-table-column>
        <yk-table-column label="报警阈值（MB）" prop="alarm" />
        <yk-table-column label="运营商" prop="autoname" />
      </el-table>
      <!--分页-->
      <el-affix target=".c_table-page" position="bottom" :offset="0">
        <yk-pagination class="c_table-pagination-page" :pages="pages" @handle="getTableData" />
      </el-affix>
    </div>
    <!--报警配置表单-->
    <el-dialog
      v-model="alarmConfigDialogModel" title="报警配置" width="365px"
      :close-on-click-modal="false" draggable
      @close="closeAlarmConfigDialog"
    >
      <el-form label-width="150px" class="mt-20">
        <el-form-item label="报警阈值（MB）：" prop="name">
          <el-input-number v-model="alarmNumber" class="el-c-input-pure" :min="0" />
          <!--<el-input-->
          <!--  v-model.trim="saveForm.name" placeholder="请输入场景名称" :maxlength="12"-->
          <!--  show-word-limit-->
          <!--  style="width: 262px"-->
          <!--/>-->
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="c_form__submit-btn">
          <el-button type="primary" plain @click="closeAlarmConfigDialog">取消</el-button>
          <el-button type="primary" @click="alarmConfigHandle">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>
